package yxy.cherry.paycenter.servlet.channel.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.cherry.paycenter.channelmodule.weixin.PayMoudle_weixin;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.servlet.channel.jh.Servlet_jh;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.game.pm2.bean.channel.SdkChannel;

public class Servlet_WeiXinPrePayAndroid extends Servlet{

	private static final int success = 1;		//成功
	private static final int dataerror = 2;		//数据错误，申请订单信息验签失败
	private static final int outtime = 3;		//超时
	private static final int orderfinsih = 4;	//订单已完成
	private static final int prepayerror = 5;	//weixin 预订单失败
	private static final int noorder = 6;		//没有这个订单
	
	private static String wx_return_success = "SUCCESS"; 	//微信预订单返回码 成功

	//支付相关
	private static int NoChannel = 6200;	//渠道不存在
	private static int NoGoods = 6201;		//商品不存在
	private static int HadGetGoods = 6202;	//商品限购，不能购买
	private static int PayFail = 6203;		//购买失败
	private static int PaySucess = 6206;	//购买成功
	
	private static final Logger logger = Logger.create(Servlet_jh.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}

	@Override
	public String getUrl() {
		return "/sdk_" + getChannel() + "pre" + PayMoudle_weixin.android;
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("doPost WeiXinIosPrePayServlet::doPost::" + req + "::"	+ req.toString());
		JSONObject rjson = new JSONObject();
		String text = HttpUtil.getPostContent(req);
		logger.info("Servlet_WeiXinPrePayAndroid text " + text);
		JSONObject tempobj = HttpUtil.URLRequestJson(text);
		
		String myorderid = tempobj.getString("myorderid");
		orders o = ordersDao.getOrderByMyorderid(myorderid);
		if(o == null) {
			rjson.put("result", noorder);
			writeResponse(resp, rjson.toString());
			return;
		}
		
		int sid = tempobj.getIntValue("sid");
		int pid = tempobj.getIntValue("pid");
		int uid = tempobj.getIntValue("uid");
		String pname = tempobj.getString("pname");
		String sdkversion = tempobj.getString("sdk");
		JSONObject itemobj = tempobj.getJSONObject("item");
		int itemid = itemobj.getIntValue("itemid");
		String itemname = itemobj.getString("name");
		double moneydouble = itemobj.getDoubleValue("money");
		int money = (int) moneydouble;

		JSONObject infoobj = tempobj.getJSONObject("info");
		JSONObject obj = new JSONObject();

		writeResponse(resp, rjson.toString());

	}

	public static void writeResponse(HttpServletResponse resp, String retstr) {
		String type = "application/x-www-form-urlencoded";
		writeResponse(resp, type, retstr);
	}

	public static void writeResponse(HttpServletResponse resp, String type, String retstr) {
		resp.setHeader("Access-Control-Allow-Origin", "*");
		resp.setHeader("Access-Control-Allow-Credentials", "true");
		resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
		resp.setHeader("Access-Control-Allow-Headers",
				"Authorization,DNT,User-Agent,Keep-Alive,Content-Type,accept,origin,X-Requested-With");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType(type);
		resp.setStatus(HttpServletResponse.SC_OK);

		PrintWriter pw = null;
		try {
			pw = resp.getWriter();
			pw.write(retstr);
		} catch (Exception e) { 
			e.printStackTrace();
		} finally {
			if (pw != null) {
				pw.flush();
				pw.close();
			}
		}
	}

	public static String getSignData(JSONObject parseobj, String scretkey, String secret) {
		// params为要参与签名的参数键值对.
		StringBuffer content = new StringBuffer();
		// 按照key做排序

		Set<String> parseset = parseobj.keySet();
		List<String> list = sortSet(parseset);

		for (int i = 0; i < list.size(); i++) {
			String key = list.get(i);
			if ("sign".equals(key))
				continue;

			String value = parseobj.getString(key);
			if (value != null) {
				content.append((i == 0 ? "" : "&") + key + "=" + value);
			}
		}

		if (scretkey != null) {
			content.append("&").append(scretkey).append("=");			
		}

		if(secret != null) {
			content.append(secret);			
		}

		return content.toString();
	}
	
	public static List<String> sortSet(Set<String> set) {
		List<String> strlist2 = new ArrayList<>();
		strlist2.addAll(set);
		Collections.sort(strlist2);

		return strlist2;
	}
	
	@Override
	public String getChannel() {
		return SdkChannel.sdk_weixin;
	}
	
}
